<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\exception\ModelEmptyException;
use app\exception\ModelException;
use app\model\InnerChart;
use app\model\SubContent;
use app\service\ContentService;
use app\validate\ContentValidate;
use think\db\exception\DbException;
use think\exception\ValidateException;

class ContentController extends BaseController
{

    // 文章批量上传
    public function articleUpload(ContentService $contentService): \think\response\Json
    {
        if($this->request->isPost()){
            $param = $this->request->param();
            $file = $this->request->file('file');
            $param['file'] = $file;
            $param['category_id'] = explode(',', $param['category_id']);

            try{
                validate(ContentValidate::class)->scene('articleUpload')->check($param);
            }catch (ValidateException $e){
                return jsonReturn(-1,$e->getError());
            }
            $param['admin'] = $this->admin;
            return  $contentService->articleUpload($param);
        }
        return jsonReturn(-1,'请求方式错误');
    }

    // 提取文章简介
    public function descExtraction(ContentService $contentService): \think\response\Json
    {
        $content = input('content');
        $res = $contentService -> descExtraction($content);
        return jsonReturn(0,'success',$res);
    }

    // 图片本地化
    public function imgLocal(ContentService $contentService): \think\response\Json
    {
        $content = input('content');
        $website = input('website');
        $res = $contentService -> imgExtraction($content,$this->admin['seller_id'],$website);
        return jsonReturn(0,'success',$res);
    }

    /**
     * 内容添加内链
     * @throws DbException
     */
    public function addInnerChat(ContentService $contentService): \think\response\Json
    {
        $param = input('post.');
        try{
            validate(ContentValidate::class)->scene('addInnerChat')->check($param);
        }catch (ValidateException $e){
            return jsonReturn(422, $e->getError());
        }
        $sellerId= $this->admin['seller_id'];
        $InnerChart = new InnerChart();
        $innerChart = $InnerChart->getAllInnerChart(['seller_id'=>$sellerId,'website_id'=>$param['website_id'],'status'=>1],'weight desc','id,weight,keyword,url,new_page_open')['data'];
        if(empty($innerChart)){
            return jsonReturn(0,'success',$param['content']);
        }
        $subId = (int)input('sub_id');
        if($subId){
            $SubContent =  new SubContent();
            $subContent = $SubContent -> getSubContent(['id'=>$subId,'seller_id'=>$this->admin['seller_id'],'is_del'=>1])['data'];
        }else{
            $subContent = null;
        }
        $content = $contentService->autoLinks($param['content'],$innerChart,$subContent);
        return jsonReturn(0,'success',$content);
    }

    /**
     * 文章列表
     *
     * @return \think\Response
     */
    public function index(ContentService $contentService): \think\Response
    {
        $categoryIds = input('param.category_id');
        $title = input('param.title');

        $limit = $this->setLimit();
        $param = [
            'seller_id' => $this->admin['seller_id'],
            'category_ids' => $categoryIds,
            'limit' => $limit,
            'lang' => input('param.lang'),
            'website_id' => (int)input('param.website_id'),
            'title' => $title
        ];
        try {
            $res = $contentService->indexContent($param);
        } catch (ModelEmptyException | ModelException | DbException $e) {
            return jsonReturn(50013,$e->getMessage());
        }
        return $res;
    }

    /**
     * 获取栏目字段
     *
     */
    public function create(ContentService $contentService): \think\response\Json
    {
        $categoryId = (int)input('category_id');
        if(!$categoryId){
            return jsonReturn(-1,'栏目ID不能为空');
        }
        $param = [
            'seller_id' => $this->admin['seller_id'],
            'category_id' => $categoryId
        ];
        try {
            $res = $contentService->createContent($param);
        } catch (ModelEmptyException | ModelException $e) {
            return jsonReturn(-3,$e->getMessage());
        }
        return $res;
    }

    /**
     * 栏目内容新增
     *
     * @return \think\Response
     */
    public function save(ContentService $contentService): \think\Response
    {
        if(!request()->isPost()){
            return jsonReturn(-2,'请求方法错误');
        }
        $param = input('post.');
        try{
            validate(ContentValidate::class)->scene('save')->check($param);
        }catch (ValidateException $e){
            return jsonReturn(422, $e->getError());
        }
        $param['admin'] = $this->admin;
        if(empty($param['sub_content']['publish_time'])){
            $param['sub_content']['publish_time'] = date('Y-m-d H:i:s',time());
        }
        if(!isset($param['main_content'])){
            $param['main_content'] = [];
        }
        try {
            $res =  $contentService->saveContent($param);
        } catch (ModelEmptyException | ModelException $e) {
            return jsonReturn(-3,$e->getMessage());
        }
        return $res;

    }

    /**
     * 显示指定的资源
     *
     */
    public function read(ContentService $contentService): \think\response\Json
    {
        $param = request()->only(['id','module_id','website_id','lang']);
        try {
            validate(ContentValidate::class)->scene('read')->check($param);
        }catch(ValidateException $e){
            return jsonReturn(-422,$e->getError());
        }
        $param['seller_id'] = $this->admin['seller_id'];
        try {
            $res = $contentService->readContent($param);
        } catch (ModelEmptyException | ModelException $e) {
            return jsonReturn(50025,$e->getMessage());
        }
        return $res;

    }

    /**
     * 保存更新的资源
     *
     * @return \think\Response
     */
    public function update(ContentService $contentService): \think\Response
    {
        if(!request()->isPost()){
            return jsonReturn(-2,'请求方法错误');
        }

        $param = input('post.');
        try{
            validate(ContentValidate::class)->scene('update')->check($param);
        }catch (ValidateException $e){
            return jsonReturn(422, $e->getError());
        }

        $param['admin'] = $this->admin;
        if(empty($param['sub_content']['publish_time'])){
            $param['sub_content']['publish_time'] = date('Y-m-d H:i:s',time());
        }
        try {
            $res =  $contentService->updateContent($param);
        } catch (ModelEmptyException | ModelException $e) {
            return jsonReturn(-3,$e->getMessage());
        }
        return $res;
    }

    /**
     * 删除指定资源
     *
     */
    public function delete(ContentService $contentService): \think\response\Json
    {
        $param = request()->only(['id','module_id']);
        try {
            validate(ContentValidate::class)->scene('delete')->check($param);
        }catch(ValidateException $e){
            return jsonReturn(-422,$e->getMessage());
        }
        $param['seller_id'] = $this->admin['seller_id'];
        $param['admin_id'] = $this->admin['uid'];
        $param['name'] = $this->admin['name'];

        return $contentService->deleteContent($param);

    }

    public function mainContent(ContentService $contentService): \think\response\Json
    {
        if(!request()->isGet()){
            return jsonReturn(-1,'请求方法错误');
        }
        $param = request()->only(['module_id','website_id','page','limit']);
        try {
            validate(ContentValidate::class)->scene('mainContent')->check($param);
        }catch(ValidateException $e){
            return jsonReturn(-422,$e->getMessage());
        }
        $limit = (int)input('param.limit') ?: 10;
        $param = [
            'seller_id' => $this->admin['seller_id'],
            'website_id' => $param['website_id'],
            'module_id' => $param['module_id'],
            'limit' => $limit,
        ];
        try {
            $res = $contentService->mainContent($param);
        } catch (ModelEmptyException | ModelException | DbException $e) {
            return jsonReturn(50013,$e->getMessage());
        }
        return $res;
    }

    /**
     * 修改置顶
     * @throws ModelException
     */
    public function topOpt(ContentService $contentService): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(ContentValidate::class)->scene('topOpt')->check($param);
            }catch(ValidateException $e){
                return jsonReturn(-422,$e->getMessage());
            }
            $param['seller_id'] = $this->admin['seller_id'];
            return $contentService->topOpt($param);
        }
        return jsonReturn(-1,'请求方法错误');
    }

    /**
     *  推荐和修改状态
     * @throws ModelException
     */
    public function recommendAndStatus(ContentService $contentService): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(ContentValidate::class)->scene('recommendAndStatus')->check($param);
            }catch(ValidateException $e){
                return jsonReturn(-422,$e->getMessage());
            }
            $param['seller_id'] = $this->admin['seller_id'];
            return $contentService->recommendAndStatus($param);
        }
        return jsonReturn(-1,'请求方法错误');
    }

    public function moduleContent(ContentService $contentService): \think\response\Json
    {
        // 关联内容
        $table = input('param.table');
//        $field = input('param.field');
        if(empty($table)){
            return jsonReturn(-1,'表名不能为空');
        }
//        if(empty($field)){
//            return jsonReturn(-2,'关联字段不能为空');
//        }

        $res = $contentService -> getModuleContent($table,$this->admin['seller_id']);
        return jsonReturn($res);
    }
}
